<template>
  <div class="cart-view">
    <h1>购物车</h1>
    <div v-if="cartItems.length > 0">
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <h3>{{ item.name }} - {{ item.price }}元</h3>
        <div class="quantity-control">
          <button @click="decrement(item.id)">-</button>
          <span>数量：{{ item.quantity }}</span>
          <button @click="increment(item.id)">+</button>
        </div>
        <button @click="removeItem(item.id)" class="remove-btn">删除</button>
      </div>
      <div class="total-price">
        <h2>总价：{{ totalPrice }}元</h2>
      </div>
    </div>
    <div v-else>
      <p>购物车为空</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CartView',
  computed: {
    cartItems() {
      return this.$store.getters.cartItems
    },
    totalPrice() {
      return this.$store.getters.totalPrice
    }
  },
  methods: {
    increment(itemId) {
      this.$store.dispatch('incrementQuantity', itemId)
    },
    decrement(itemId) {
      this.$store.dispatch('decrementQuantity', itemId)
    },
    removeItem(itemId) {
      this.$store.dispatch('removeItem', itemId)
    }
  }
}
</script>

<style scoped>
.cart-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.cart-item {
  border: 1px solid #ddd;
  padding: 15px;
  margin: 10px 0;
  border-radius: 5px;
}

.quantity-control {
  margin: 10px 0;
}

.quantity-control button {
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
}

.remove-btn {
  background-color: #ff4444;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
}

.remove-btn:hover {
  background-color: #cc0000;
}

.total-price {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 5px;
}
</style>